package ar.com.solidussource.howmuchservices.web.controller;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import ar.com.solidussource.framework.backend.bo.exception.BusinessException;
import ar.com.solidussource.framework.backend.dao.filter.Page;
import ar.com.solidussource.framework.backend.dao.filter.Result;
import ar.com.solidussource.framework.backend.dao.filter.TableOrder;
import ar.com.solidussource.howmuchservices.backend.bo.LocationCRUDBO;
import ar.com.solidussource.howmuchservices.backend.bo.ProvinceCRUDBO;
import ar.com.solidussource.howmuchservices.common.entities.Location;
import ar.com.solidussource.howmuchservices.common.entities.Province;
import ar.com.solidussource.howmuchservices.common.entities.filter.LocationFilter;
import ar.com.solidussource.howmuchservices.utils.json.JSONUtils;

@Controller
@RequestMapping("/location")
public class LocationController extends BaseController {
	private static final Logger log = Logger.getLogger(LocationController.class);
	private static final String TABLEORDER_CRITERION = "name";
	private static final String TABLEORDER_DIRECTION = "desc";
	
	@Autowired ProvinceCRUDBO provinceCRUDBO;
	@Autowired LocationCRUDBO locationCRUDBO; 	
	
	@RequestMapping(value="/list.json", method = RequestMethod.GET, produces="application/json")
	@ResponseBody
	public String getLocationsByProvinceId(HttpServletResponse httpServletResponse, @RequestParam Integer provinceId, @RequestParam Integer pageNumber, @RequestParam Integer size) {
		
		try {
			Province province = provinceCRUDBO.getById(provinceId);
			
			if (province != null) {
				
				LocationFilter locationFilter = new LocationFilter(); 
				locationFilter.setProvinceId(provinceId);
				locationFilter.setTableOrder(new TableOrder(TABLEORDER_CRITERION, TABLEORDER_DIRECTION));
				
				Page page = new Page(pageNumber, size);
				
				Result<Location> locations = locationCRUDBO.getAll(locationFilter, page);
				
				return JSONUtils.getJSON(locations.getResult());			
				
			} else {
				throw new BusinessException("no province "+provinceId);				
			}			

			
		} catch (Exception e) {
			httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			log.error(e.getMessage(), e);			
			return getJsonStatus(e.getMessage());
		}

	}	
}
